package io.renren.learn.filter;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @author Administrator
 */
@Component
@ConfigurationProperties(prefix = "server")
public class PortFilter implements Filter {


    private Map<String, String> ports;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest http = (HttpServletRequest) servletRequest;
        int port = http.getServerPort();
        String uri = http.getRequestURI();
        if (null == ports.get(String.valueOf(port)) || !uri.contains(ports.get(String.valueOf(port)))) {
            Assert.isTrue(false, "非法访问!");
        }
        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {

    }

    public void setPorts(Map<String, String> ports) {
        this.ports = ports;
    }
}
